package com.atguigu.com.gulimallouth.controller;

import com.atguigu.com.gulimallouth.constant.SmsConstant;
import com.atguigu.com.gulimallouth.feign.ThirdFeign;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.sun.org.apache.xalan.internal.xsltc.dom.DocumentCache;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.stream.IIOByteBuffer;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class SmsController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ThirdFeign thirdFeign;

    @GetMapping("/sms/sendCode")
    public R smsCode(@RequestParam("phone") String phone){
        //接口防刷
        //1.1先获取reids中的验证码
        String s1 = redisTemplate.opsForValue().get(SmsConstant.SMS_PHONE + phone);
        if (!StringUtils.isEmpty(s1)){
            long millis = System.currentTimeMillis();
            long l = Long.parseLong(s1.split("_")[1]);
            if (millis-l<60000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //生成一个随机的6位数验证吗
        String code = UUID.randomUUID().toString().substring(0, 5);
        //设置验证码+生成验证码的时间 防止接口重复发送
        String s = code + "_" + System.currentTimeMillis();
        //设置过期时间
        redisTemplate.opsForValue().set(SmsConstant.SMS_PHONE+phone,s, 10,TimeUnit.MINUTES);
        //发送验证码
        thirdFeign.SmsPhone(phone, code);

        return R.ok();
    }
}
